package phase01.module4.code.question2;

import java.io.File;
import java.util.Objects;
import java.util.Scanner;

public class DeleteAll {

    private static void deleteFile(File f) {
        boolean deleted;
        if(f.isDirectory() && f.canWrite()) {
            File[] children = f.listFiles();
            if (Objects.requireNonNull(children).length > 0) {
                for (File file: children) {
                    if(file.isFile() && file.canWrite()) {
                        deleted = file.delete();
                        if (deleted) {
                            System.out.println("文件" + file.getAbsolutePath() + "被删除.");
                        }
                    }
                    if(file.isDirectory() && file.canWrite()) {
                        deleteFile(file);
                    }
                }
            } else {
                deleted = f.delete();
                if (deleted) {
                    System.out.println("文件" + f.getAbsolutePath() + "被删除.");
                }
            }
        }
        if(f.isFile() && f.canWrite()) {
            deleted = f.delete();
            if (deleted) {
                System.out.println("文件" + f.getAbsolutePath() + "被删除.");
            }
        }
    }
    private static void deleteAll(File target) {
        if(target.isDirectory()) {
            if(!target.canWrite()) {
                System.out.println("没有权限删除！");
                return;
            }
            File[] children = target.listFiles();
            if(Objects.requireNonNull(children).length > 0) {
                for(File f: children) {
                    deleteFile(f);
                }
            } else {
                System.out.println("文件夹" + target.getAbsolutePath() + "为空!");
            }
        } else {
            System.out.println(target.getAbsolutePath() + "不是一个文件夹!");
        }
    }
    public static void main(String[] args) {
        String targetPath;
        Scanner scanner = new Scanner(System.in);
        targetPath = scanner.next();
        File targetFile = new File(targetPath);
        if(targetFile.isDirectory() && targetFile.canWrite()) {
            // delete all files/folders
            deleteAll(targetFile);
        }
    }
}
